package com.yanqu.road.server.timer.marriage;

import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.server.manger.relatives.RelativesMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.utils.executor.GeneralTask;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

public class RelativesUserInfoUpdateTask extends GeneralTask {

    private static final Logger logger = LogManager.getLogger(RelativesUserInfoUpdateTask.class);

    private int times;

    private int count = 10;

    @Override
    public void doRun() {

        times++;

        try{
            if((times % count) % 2 == 0){
                RelativesMgr.fetchCrossRelativesUserInfo();
            }
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }

        try{
            if(CrossUnionMgr.isAllSync() && times % count == 0){
                //商会分组大于联姻分组，直接同步member的userBaseInfo
                Map<Long, UserBaseInfo> tempMap = new HashMap<>();
                for (Map.Entry<Long, UserBaseInfo> entry : RelativesMgr.getCacheOtherServerUserMap().entrySet()) {
                    long userId = entry.getKey();
                    CrossUnionMember member = CrossUnionMgr.getDeleteUnionMemberMap().get(userId);
                    if(member != null){
                        tempMap.put(userId, member.getUserBaseInfo());
                        continue;
                    }
                    for (Map.Entry<String, Map<Long, CrossUnionMember>> mapEntry : CrossUnionMgr.getUnionMemberMap().entrySet()) {
                        member = mapEntry.getValue().get(userId);
                        if(member != null){
                            tempMap.put(userId, member.getUserBaseInfo());
                        }
                    }
                }
                for (Map.Entry<Long, UserBaseInfo> infoEntry : tempMap.entrySet()) {
                    RelativesMgr.getCacheOtherServerUserMap().put(infoEntry.getKey(), infoEntry.getValue());
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }

    }
}
